package com.example.rpapp.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.config.exception.RLdCodeException;
import com.example.config.util.JwtUtil;
import com.example.rpapp.user.command.UserRegisterCmdExe;
import com.example.rpapp.user.command.UserUpdateCmdExe;
import com.example.rpapp.user.query.UserListByParamQueryExe;
import com.example.rpapp.user.query.UserLoginQueryExe;
import com.example.rpclient.UserRegisterCmd;
import com.example.rpclient.api.IUserService;
import com.example.rpclient.dto.UserUpdateCmd;
import com.example.rpclient.dto.data.UserVo;
import com.example.rpclient.dto.query.UserListByParamQuery;
import com.example.rpclient.dto.query.UserLoginQuery;
import com.example.rpclient.feign.WalletFeignApi;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Map;

@Slf4j
@Service
@AllArgsConstructor
public class UserServiceImpl implements IUserService {

    private final UserRegisterCmdExe userRegisterCmdExe;

    private final UserLoginQueryExe userLoginQueryExe;

    private final UserListByParamQueryExe userListByParamQueryExe;

    private final UserUpdateCmdExe userUpdateCmdExe;

    private final WalletFeignApi walletFeignApi;

    @Override
    public UserVo register(UserRegisterCmd cmd) {
        UserVo execute = userRegisterCmdExe.execute(cmd);

        try {
            walletFeignApi.initUserWallet(execute.getId());
        } catch (Exception e) {
            //错误处理
            log.error("用户注册成功，但初始化用户钱包失败：", e);
        }

        return execute;
    }

    @Override
    public String login(UserLoginQuery query) {
        UserVo userVo = userLoginQueryExe.execute(query);
        return JwtUtil.createToken(Map.of(
                "username", userVo.getUsername(),
                "name", userVo.getName(),
                "phone", userVo.getPhone(),
                "id", userVo.getId()
        ));
    }

    @Override
    public IPage<UserVo> page(UserListByParamQuery paramQuery) {
        return userListByParamQueryExe.execute(paramQuery);
    }

    @Override
    public UserVo one(Long id) {
        final var query = new UserListByParamQuery();
        query.setId(id);
        IPage<UserVo> iPage = userListByParamQueryExe.execute(query);

        if (CollUtil.isEmpty(iPage.getRecords())) {
            throw new RLdCodeException("该用户不存在！");
        }
        return iPage.getRecords().get(0);
    }

    @Override
    public UserVo update(UserUpdateCmd cmd) {
        return userUpdateCmdExe.execute(cmd);
    }
}
